package struts.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.action.Action;
import struts.action.ActionForm;

import struts.util.FullForm;
import struts.util.XmlBean;


public class ActionServlet extends HttpServlet {


	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String servletPath=request.getServletPath(); //
		String path= this.getPath(servletPath); // 
		Map<String,XmlBean> map=(Map<String, XmlBean>)this.getServletContext().getAttribute("strutsConfig");
		XmlBean xmlBean=map.get(path);
		String formBeanType = xmlBean.getFormBeanType();
		ActionForm form=FullForm.fill(formBeanType, request);
		
		String actionType = xmlBean.getActionType();
		
		Action action=null;
		String url="";
		try {
			Class clazz = Class.forName(actionType);
			 action=(Action) clazz.newInstance();
			url=action.execute(request, form, xmlBean.getActionForward());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		RequestDispatcher rd=request.getRequestDispatcher(url);
		rd.forward(request, response);
		
		
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}
 private String getPath(String servletPath){
	  return servletPath.split("\\.")[0];
	  
  }

}
